import yizhi_html_escape_1 from "yizhi-html-escape";

import { parseLyricTag,genLyricTag} from "./lyricCommon"

/**
 * 解析KRC歌词
 * @param krcText KRC歌词文本内容
 */
export function parse(krcText) {
    //结果
    const result = { type: "KARA", content: [] };
    //逐行处理
    krcText.split(/\r?\n/).forEach(line => {
        line = line.trim();
        //歌词行
        const match = line.match(/^\[\s*(\d+)\s*,\s*(\d+)\s*\](.*)$/);
        if (match) {
            //目标信息
            const lrcLine = {
                start: parseInt(match[1]),
                duration: parseInt(match[2]),
                content: [],
            };
            //一直往后所搜词语
            let rem = match[3];
            while (rem.length) {
                const match = rem.match(/^<(\d+),(\d+),(\d+)>([^<]+)/);
                if (match) {
                    const word = {
                        start: parseInt(match[1]),
                        duration: parseInt(match[2]),
                        content: (0, yizhi_html_escape_1.unescape)(match[4]),
                    };
                    if (word.content)
                        lrcLine.content.push(word);
                    rem = rem.substring(match[0].length);
                }
                else
                    break;
            }
            //保存行
            if (lrcLine.content.length)
                result.content.push(lrcLine);
        }
        //标签
        else
            parseLyricTag(result, line);
    });
    return result;
}

/**
 * 将歌词转换为KRC文本
 * @param lyric 歌词(只能是卡拉OK歌词)
 */
export function stringify(lyric) {
    if (lyric.type !== "KARA"){
        throw new Error(`lrc cannot stringify to krc`);
    }

    const buffer = [...genLyricTag(lyric)];
    lyric.content.forEach(line => {
        if (typeof line.content === 'string')
            return;
        const dur = line.duration ?? (() => {
            const last = line.content[line.content.length - 1];
            if (!last)
                return 0;
            return last.start + line.start + last.duration;
        })();
        const text = line.content.map(word => `<${word.start},${word.duration},0>${word.content}`).join('');
        buffer.push(`[${line.start},${dur}]${text}`);
    });
    return buffer.join('\n');
}


